package com.dhcc.demo.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.dhcc.cdc.busi.entity.CdcDictionaryEntity;
import com.dhcc.cdc.busi.entity.CdcExaminateEntity;
import com.dhcc.cdc.busi.service.ICdcDictionaryService;
import com.dhcc.cdc.busi.service.ICdcExaminationService;
import com.dhcc.cdc.sys.entity.CdcDataEntity;
import com.dhcc.cdc.sys.service.ICdcDataService;
import com.dhcc.core.api.controller.BaseApiController;
import com.dhcc.core.framework.result.R;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.sdc.api.function.IntheCheck;
import com.dhcc.sds.busi.service.ISdsQcincaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Method;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * API接收数据接口
 * 
 * @ClassName: ApiReceiveDataController
 * @Description: TODO
 * @author: zx
 * @date: 2023年06月02日 上午10:04:55
 */
@RestController
@RequestMapping("${sys.apiPath}")
@Api("接收数据接口")
public class ApiReceiveDataController extends BaseApiController {
    @Autowired
    private ICdcExaminationService cdcExaminationService;
    @Autowired
    private ICdcDictionaryService cdcDictionaryService;
    @Autowired
    private ICdcDataService cdcDataService;
    /**
     * 检查报告接口
     */
    @PostMapping("sendExamReport")
    @ApiOperation(value = "检查报告信息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", dataType = "string", name = "message", value = "检查报告", required = true) })
    @ResponseBody
    public R sendExamReport(@RequestParam(required = true)  String message) {
        try {
            Document document = DocumentHelper.parseText(message);
            Element rootElement =document.getRootElement();
            List<Element> reports = rootElement.elements();
            if(CommonUtil.isNotEmpty(reports)){
                for(int i=0;i<reports.size();i++){
                    Element report = reports.get(i);
                    updateReport(report);
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        } catch (Exception e){
            e.printStackTrace();
            return R.error(e.getMessage());
        }
        return R.ok("操作成功！");
    }

    /**
     *
     * @param element
     * @throws Exception
     * 插入/更新/删除检查报告
     */
    private void updateReport(Element element)throws Exception{
        Element opercode = element.element("operCode");
        String opercodeV = opercode.getStringValue();
        if("0".equals(opercodeV)){//删除
            Wrapper<CdcExaminateEntity> wrapper = new EntityWrapper<CdcExaminateEntity>();
            wrapper.eq("xcode", element.element("xcode").getStringValue());
            wrapper.eq("episode_id", element.element("episodeId").getStringValue());
            cdcExaminationService.delete(wrapper);
        }else if("1".equals(opercodeV)){//新增
            CdcExaminateEntity exam = new CdcExaminateEntity();
            setExamValue(exam,element);
            cdcExaminationService.insert(exam);
        }else if("2".equals(opercodeV)){//修改
            Map map = new HashMap();
            map.put("xcode", element.element("xcode").getStringValue());
            map.put("episodeId", element.element("episodeId").getStringValue());
            List<CdcExaminateEntity> exams = cdcExaminationService.list(map);
            if(CommonUtil.isNotEmpty(exams)){
                if(exams.size()>1){
                    throw new Exception("根据episodeId和xcode找到多条检查报告数据！");
                }
                setExamValue(exams.get(0),element);
                cdcExaminationService.updateById(exams.get(0));
            }
        }
    }
    /**
     * 根据传入的参数，设置检查报告实体的值
     *
     * */
    private void setExamValue(CdcExaminateEntity exam,Element element) {
        List<Element> eles = element.elements();
        Date date = null;
        //date_id
        CdcDataEntity cdcData = cdcDataService.selectByCode("ExamData");
        exam.setDataId(cdcData.getId());
        for (int i = 0; i < eles.size(); i++) {
            switch (eles.get(i).getName()) {
                case "xcode":
                    exam.setXcode(eles.get(i).getText());
                    break;
                case "episodeId":
                    exam.setEpisodeId(Long.parseLong(eles.get(i).getText()));
                    break;
                case "examNum":
                    exam.setExamNum(eles.get(i).getText());
                    break;
                case "bsOrdexecId":
                    exam.setBsOrdexecId(Long.parseLong(eles.get(i).getText()));
                    break;
                case "busExamReportStatusId":
                    Map map = new HashMap();
                    map.put("dictypeId", "1405696298799112194");
                    List<CdcDictionaryEntity> dict = cdcDictionaryService.list(map);
                    for (int j = 0; j < dict.size(); j++) {
                        if (dict.get(j).getCode().equals(eles.get(i).getText())) {
                            exam.setBusExamReportStatusId(dict.get(j).getId());
                            break;
                        }
                    }
                    break;
                case "description":
                    exam.setDescription(eles.get(i).getText());
                    break;
                case "examDesc":
                    exam.setExamDesc(eles.get(i).getText());
                    break;
                case "resultDesc":
                    exam.setResultDesc(eles.get(i).getText());
                    break;
                case "repUserName":
                    exam.setRepUserName(eles.get(i).getText());
                    break;
                case "repDate":
                    try {
                        date = new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(eles.get(i).getText().toString()).getTime());
                    }catch (ParseException e){
                        e.printStackTrace();
                    }
                    exam.setRepDate(date);
                    break;
                case "regUserName":
                    exam.setRegUserName(eles.get(i).getText());
                    break;
                case "regDate":
                    try {
                        date = new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(eles.get(i).getText().toString()).getTime());
                    }catch (ParseException e){
                        e.printStackTrace();
                    }
                    exam.setRegDate(date);
                    break;
                case "updateDate":
                    try {
                        date = new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(eles.get(i).getText().toString()).getTime());
                    }catch (ParseException e){
                        e.printStackTrace();
                    }
                    exam.setUpdateDate(date);
                    break;
                case "updateBy":
                    exam.setUpdateBy(eles.get(i).getText());
                    break;
            }
        }
//        /**
//         * 按照CDSS写的接口，很多字段对不上
//         *
//         * */
//    private void analysisExamReport(String name ,String value,CdcExaminateEntity exam){
//        switch (name) {
//            case "IDNO":
//                exam.setXcode(value);
//                break;
//            case "PatientDR":
//                exam.setEpisodeId(Long.parseLong(value));
//                break;
//            case "VisitID":
//            case "VisitType":
//            case "GroupFlag":
//                exam.setBsOrdexecId(Long.parseLong(value));
//                break;
//            case "GroupSequence":
//            case "ExamCode":
//                exam.setExamNum(value);
//                break;
//            case "ExamName":
//                exam.setDescription(value);
//                break;
//            case "ExamResultNum":
//            case "ExamResult":
//            case "ExamResultFlag":
//            case "ExamResultDesc":
//                exam.setResultDesc(value);
//            case "PartDR":
//            case "ExecuteTime":
//            case "ReportTime":
//                exam.setRepDate(Date.valueOf(value));
//            case "Remarks":
//
//    }

    }}
